package itsm.isperp.module.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.bpm.BpmActionHistory;
import itsm.isperp.module.entity.bpm.BpmNodeUser;
import itsm.isperp.module.entity.db.DbEntity;
import itsm.isperp.module.service.app.AppRoleService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.bpm.BpmActionHistoryService;
import itsm.isperp.module.service.bpm.BpmNodeUserService;
import itsm.isperp.module.service.bpm.BpmProcessSettingService;
import itsm.isperp.module.service.project.ProjProjectMemberService;
import itsm.isperp.workflow.utils.BpmConst;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.engine.delegate.VariableScope;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-9-3
 * @since 1.0
 * 
 */
public class CandidaterUtils {
	// 针对流程监听器的方法
	public static final void addToCandidaterInProcess(
			BpmNodeUserService service, Map<String, IUser> mapUsers,
			final BpmNodeUser user, String businessKey, String processdefId,
			String processId, String nodeId, VariableScope delegateTask) {
		AppRoleService appRoleService = ContextHolder
				.getSpringBean("appRoleService");
		AppUserService appUserService = ContextHolder
				.getSpringBean("appUserService");
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		BpmProcessSettingService setting = ContextHolder
				.getSpringBean("bpmProcessSettingService");
		switch (user.getAssignType()) {
		case 0:

			String starter = delegateTask.getVariable("bpmStarter").toString();
			if (!mapUsers.containsKey(starter)) {
				mapUsers.put(starter, appUserService.findByUsername(starter));
			}
			break;
		case 10:
			String bpmCurrentUser = (String) delegateTask
					.getVariable("bpmCurrentUser");

			if (StringUtils.isNotEmpty(bpmCurrentUser)) {
				if (!mapUsers.containsKey(bpmCurrentUser)) {
					mapUsers.put(bpmCurrentUser,
							appUserService.findByUsername(bpmCurrentUser));
				}
			}

			break;
		case 1:
			// 特定角色

			List<? extends IUser> us = appRoleService.findRoleMembers(user
					.getCmpIds());
			for (IUser u : us) {
				if (!mapUsers.containsKey(u.getUsername())) {
					mapUsers.put(u.getUsername(), u);
				}
			}

			break;
		case 11:
			// 项目中的特定角色

			Map<String, Object> domainMap = service
					.findDbEntityWithDomainFieldByNodeId(user
							.getBpmNodeSettingId());

			if (MapUtils.isEmpty(domainMap)) {
				return;
			}

			String sql = "SELECT " + domainMap.get("column_name").toString()
					+ " FROM " + domainMap.get("table_name") + " WHERE id=?";

			Map<String, Object> projectIdMap = jdbcTemplate.queryForMap(sql,
					businessKey);

			if (MapUtils.isEmpty(projectIdMap)) {
				return;
			}

			ProjProjectMemberService projProjectMemberService = ContextHolder
					.getSpringBean("projProjectMemberService");

			us = projProjectMemberService.findMemberUserByProjectIdAndRole(
					projectIdMap.get(domainMap.get("column_name").toString())
							.toString(), user.getCmpIds());

			for (IUser u : us) {
				if (!mapUsers.containsKey(u.getUsername())) {
					mapUsers.put(u.getUsername(), u);
				}
			}
			break;
		case 2:
			// 指定人员
			if (!mapUsers.containsKey(user.getCmpIds())) {
				mapUsers.put(user.getCmpIds(),
						appUserService.findByUsername(user.getCmpIds()));
			}
			break;
		case 3:
		case 31:

			DbEntity entity = setting.findDbEntityByKey(processdefId);

			sql = "SELECT " + user.getCmpIds() + " FROM "
					+ entity.getTableName() + " WHERE id=?";

			Map<String, Object> result = jdbcTemplate.queryForMap(sql,
					businessKey);
			if (result == null || result.size() == 0
					|| result.get(user.getCmpIds()) == null) {
				return;
			}
			String uName = result.get(user.getCmpIds()).toString();

			JqGridRequest req = new JqGridRequest();
			req.isPageable(false);
			String field = "id";
			if (user.getAssignType() == 3) {
				field = "name";
			}

			if (uName.contains(",")) {
				String uNames = "'" + uName.replaceAll(",", "','") + "'";
				req.addFilterRule(field, JqGridFilterRuleOp.in, uNames);

			} else {
				req.addFilterRule(field, JqGridFilterRuleOp.eq, uName);
			}

			List<AppUser> vus = appUserService.findAll(req);

			for (AppUser vu : vus) {
				if (!mapUsers.containsKey(vu.getUsername())) {
					mapUsers.put(vu.getUsername(), vu);
				}

			}

			break;

		case 4:
			// 特定部门下所有成员
			List<? extends IUser> userList = appUserService.findByDeptId(user
					.getCmpIds());
			for (IUser u : userList) {
				if (!mapUsers.containsKey(u.getUsername())) {
					mapUsers.put(u.getUsername(), u);
				}
			}
			break;
		case 5:
			// 任务处理人

			String qSql = BpmConst.getQueryUsersByTask(processId, nodeId);

			jdbcTemplate = ContextHolder.getSpringBean(JdbcTemplate.class);

			List<Map<String, Object>> l = jdbcTemplate.queryForList(qSql);

			for (Map<String, Object> m : l) {
				String username = m.get("name").toString();
				if (!mapUsers.containsKey(username)) {
					appUserService = ContextHolder
							.getSpringBean("appUserService");
					IUser u = appUserService.findByUsername(username);
					mapUsers.put(username, u);
				}
			}

			break;

		}

	}

	// 针对流程监听器的方法
	public static final void addToCandidaterInProcess(
			BpmNodeUserService service, Set<String> mapUsers,
			final BpmNodeUser user, String businessKey, String processdefId,
			VariableScope delegateTask) {

		AppRoleService appRoleService = ContextHolder
				.getSpringBean("appRoleService");
		AppUserService appUserService = ContextHolder
				.getSpringBean("appUserService");
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		BpmProcessSettingService setting = ContextHolder
				.getSpringBean("bpmProcessSettingService");

		switch (user.getAssignType()) {
		case 0:
			String starter = delegateTask.getVariable("bpmStarter").toString();
			if (!mapUsers.contains(starter)) {
				mapUsers.add(starter);
			}
			break;
		case 10:
			String bpmCurrentUser = (String) delegateTask
					.getVariable("bpmCurrentUser");

			if (StringUtils.isNotEmpty(bpmCurrentUser)) {
				if (!mapUsers.contains(bpmCurrentUser)) {
					mapUsers.add(bpmCurrentUser);
				}
			}

			break;
		case 1:
			// 按角色
			List<? extends IUser> us = appRoleService.findRoleMembers(user
					.getCmpIds());
			for (IUser u : us) {
				if (!mapUsers.contains(u.getUsername())) {
					mapUsers.add(u.getUsername());
				}
			}
			break;

		case 11:
			// 项目中的角色成员

			Map<String, Object> domainMap = service
					.findDbEntityWithDomainFieldByNodeId(user
							.getBpmNodeSettingId());

			if (MapUtils.isEmpty(domainMap)) {
				return;
			}

			String sql = "SELECT " + domainMap.get("column_name").toString()
					+ " FROM " + domainMap.get("table_name") + " WHERE id=?";

			Map<String, Object> projectIdMap = jdbcTemplate.queryForMap(sql,
					businessKey);

			if (MapUtils.isEmpty(projectIdMap)) {
				return;
			}

			ProjProjectMemberService projProjectMemberService = ContextHolder
					.getSpringBean("projProjectMemberService");

			us = projProjectMemberService.findMemberUserByProjectIdAndRole(
					projectIdMap.get(domainMap.get("column_name").toString())
							.toString(), user.getCmpIds());

			for (IUser u : us) {
				if (!mapUsers.contains(u.getUsername())) {
					mapUsers.add(u.getUsername());
				}
			}
			break;
		case 2:
			// 指定人员
			if (!mapUsers.contains(user.getCmpIds())) {
				mapUsers.add(user.getCmpIds());
			}
			break;
		case 3:
		case 31:
			// 表单内特定成员--使用帐号保存
			DbEntity entity = setting.findDbEntityByKey(processdefId);

			sql = "SELECT " + user.getCmpIds() + " FROM "
					+ entity.getTableName() + " WHERE id=?";

			Map<String, Object> result = jdbcTemplate.queryForMap(sql,
					businessKey);
			if (result == null || result.size() == 0) {
				return;
			}
			String uName = result.get(user.getCmpIds()).toString();

			JqGridRequest req = new JqGridRequest();
			req.isPageable(false);
			String field = "id";
			if (user.getAssignType() == 3) {
				field = "name";
			}

			if (uName.contains(",")) {
				String uNames = "'" + uName.replaceAll(",", "','") + "'";
				req.addFilterRule(field, JqGridFilterRuleOp.in, uNames);

			} else {
				req.addFilterRule(field, JqGridFilterRuleOp.eq, uName);
			}

			List<AppUser> vus = appUserService.findAll(req);

			for (AppUser vu : vus) {

				mapUsers.add(vu.getUsername());

			}
			break;
		case 4:
			// 部门
			List<? extends IUser> userList = appUserService.findByDeptId(user
					.getCmpIds());
			for (IUser u : userList) {
				if (!mapUsers.contains(u.getUsername())) {
					mapUsers.add(u.getUsername());
				}
			}
			break;

		}

	}

	

	
	// 针对普通方法调用的方法
	public static final void addToCandidater(BpmNodeUserService service,
			Map<String, IUser> mapUsers, String processInstanceId,
			final BpmNodeUser user, String processdefId,
			final String businessKey) {
		AppRoleService appRoleService = ContextHolder
				.getSpringBean("appRoleService");
		AppUserService appUserService = ContextHolder
				.getSpringBean("appUserService");
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		BpmProcessSettingService setting = ContextHolder
				.getSpringBean("bpmProcessSettingService");
		switch (user.getAssignType()) {
		case 0:
			// 通过查询获取发起人
			BpmActionHistoryService bpmActionHistoryService = ContextHolder
					.getSpringBean("bpmActionHistoryService");
			BpmActionHistory bh = bpmActionHistoryService
					.findStartByProcessId(processInstanceId);
			if (!mapUsers.containsKey(bh.getActionUserId())) {

				IUser us = appUserService.findByUsername(bh.getActionUserId());

				if (!mapUsers.containsKey(us.getUsername())) {
					mapUsers.put(us.getUsername(), us);
				}
			}

			break;

		case 10:
			// 取得上一步的处理人
			IUser currentuser = ContextHolder.getLoginUser();
			if (!mapUsers.containsKey(currentuser.getUsername())) {
				mapUsers.put(currentuser.getUsername(), currentuser);
			}

			break;
		case 1:
			// 按角色

			List<? extends IUser> us = appRoleService.findRoleMembers(user
					.getCmpIds());
			for (IUser u : us) {
				if (!mapUsers.containsKey(u.getUsername())) {
					mapUsers.put(u.getUsername(), u);
				}
			}
			break;

		case 11:
			// 项目中的角色成员

			Map<String, Object> domainMap = service
					.findDbEntityWithDomainFieldByNodeId(user
							.getBpmNodeSettingId());

			if (MapUtils.isEmpty(domainMap)) {
				return;
			}

			String sql = "SELECT " + domainMap.get("column_name").toString()
					+ " FROM " + domainMap.get("table_name") + " WHERE id=?";

			Map<String, Object> projectIdMap = jdbcTemplate.queryForMap(sql,
					businessKey);

			if (MapUtils.isEmpty(projectIdMap)) {
				return;
			}

			ProjProjectMemberService projProjectMemberService = ContextHolder
					.getSpringBean("projProjectMemberService");

			us = projProjectMemberService.findMemberUserByProjectIdAndRole(
					projectIdMap.get(domainMap.get("column_name").toString())
							.toString(), user.getCmpIds());

			for (IUser u : us) {
				if (!mapUsers.containsKey(u.getUsername())) {
					mapUsers.put(u.getUsername(), u);
				}
			}
			break;
		case 2:
			// 指定人员

			IUser u = appUserService.findByUsername(user.getCmpIds());
			if (!mapUsers.containsKey(u.getUsername())) {
				mapUsers.put(u.getUsername(), u);
			}
			break;
		case 3:
		case 31:
			// 表单内特定成员--使用帐号保存

			DbEntity entity = setting.findDbEntityByKey(processdefId);

			sql = "SELECT " + user.getCmpIds() + " FROM "
					+ entity.getTableName() + " WHERE id=?";

			Map<String, Object> result = jdbcTemplate.queryForMap(sql,
					businessKey);
			if (result == null || result.size() == 0) {
				return;
			}

			String uName = result.get(user.getCmpIds()).toString();

			JqGridRequest req = new JqGridRequest();
			req.isPageable(false);
			String field = "id";
			if (user.getAssignType() == 3) {
				field = "name";
			}

			if (uName.contains(",")) {
				String uNames = "'" + uName.replaceAll(",", "','") + "'";
				req.addFilterRule(field, JqGridFilterRuleOp.in, uNames);

			} else {
				req.addFilterRule(field, JqGridFilterRuleOp.eq, uName);
			}

			List<AppUser> vus = appUserService.findAll(req);

			for (AppUser vu : vus) {
				if (!mapUsers.containsKey(vu.getUsername())) {
					mapUsers.put(vu.getUsername(), vu);
				}

			}
			break;
		case 4:
			// 部门
			/*List<? extends IUser> userList = appUserService.findByDeptId(user
					.getCmpIds());*/
			//包含子部门人员
			List<AppUser> userList = appUserService.findUserByTopDeptIdByRequest(user
					.getCmpIds());
			for (AppUser uu : userList) {
				if (!mapUsers.containsKey(uu.getName())) {
					mapUsers.put(uu.getName(), uu);
				}
			}
			break;
		case 6:
			//特定步骤下的处理人
			String sql1="SELECT * FROM `act_hi_taskinst` WHERE PROC_INST_ID_='"+processInstanceId+"' and END_TIME_ IS NOT NULL and TASK_DEF_KEY_='"+user.getCmpIds()+"'";
			List<Map<String,Object>> list=jdbcTemplate.queryForList(sql1);
			for(int i=0;i<list.size();i++)
			{
				String userName=list.get(0).get("ASSIGNEE_").toString();
				AppUser u1=appUserService.findByUsername(userName);
				mapUsers.put(u1.getName(), u1);
			}
			break;

		}

	}
}
